package service

import (
	"context"

	pb "medicine/api/medicine/v1"
	"medicine/internal/biz"

	"github.com/go-kratos/kratos/v2/log"
)

// PointsService 积分服务
type PointsService struct {
	pb.UnimplementedPointsServer

	uc  *biz.PointsUsecase
	log *log.Helper
}

// NewPointsService 创建积分服务实例
func NewPointsService(uc *biz.PointsUsecase, logger log.Logger) *PointsService {
	return &PointsService{
		uc:  uc,
		log: log.NewHelper(logger),
	}
}

// AddPointsForConsumption 消费成功后赠送积分
func (s *PointsService) AddPointsForConsumption(ctx context.Context, req *pb.AddPointsForConsumptionRequest) (*pb.AddPointsForConsumptionReply, error) {
	pointsAdded, totalPoints, err := s.uc.AddPointsForConsumption(ctx, req.UserId, req.OrderId, req.Amount, req.OrderType)
	if err != nil {
		s.log.Errorf("消费赠送积分失败: %v", err)
		return nil, err
	}

	return &pb.AddPointsForConsumptionReply{
		PointsAdded: pointsAdded,
		TotalPoints: totalPoints,
		Message:     "积分赠送成功",
	}, nil
}

// AddPointsForCheckin 签到获取积分
func (s *PointsService) AddPointsForCheckin(ctx context.Context, req *pb.AddPointsForCheckinRequest) (*pb.AddPointsForCheckinReply, error) {
	pointsAdded, totalPoints, checkinDays, err := s.uc.AddPointsForCheckin(ctx, req.UserId)
	if err != nil {
		s.log.Errorf("签到获取积分失败: %v", err)
		return nil, err
	}

	return &pb.AddPointsForCheckinReply{
		PointsAdded: pointsAdded,
		TotalPoints: totalPoints,
		CheckinDays: checkinDays,
		Message:     "签到成功",
	}, nil
}

// UsePoints 使用积分
func (s *PointsService) UsePoints(ctx context.Context, req *pb.UsePointsRequest) (*pb.UsePointsReply, error) {
	success, remainingPoints, err := s.uc.UsePoints(ctx, req.UserId, req.Points, req.Purpose)
	if err != nil {
		s.log.Errorf("使用积分失败: %v", err)
		return nil, err
	}

	return &pb.UsePointsReply{
		Success:         success,
		RemainingPoints: remainingPoints,
		Message:         "操作完成",
	}, nil
}

// GetPointsRules 获取积分规则
func (s *PointsService) GetPointsRules(ctx context.Context, req *pb.GetPointsRulesRequest) (*pb.GetPointsRulesReply, error) {
	rules, err := s.uc.GetPointsRules(ctx)
	if err != nil {
		s.log.Errorf("获取积分规则失败: %v", err)
		return nil, err
	}

	var pbRules []*pb.PointsRule
	for _, rule := range rules {
		pbRules = append(pbRules, &pb.PointsRule{
			Type:        rule.Type,
			Name:        rule.Name,
			Description: rule.Description,
			Rate:        rule.Rate,
			MinAmount:   rule.MinAmount,
			MaxPoints:   rule.MaxPoints,
			Enabled:     rule.Enabled,
		})
	}

	return &pb.GetPointsRulesReply{
		Rules:   pbRules,
		Message: "获取成功",
	}, nil
}
